﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WeChatParking.Entity.Enums;

namespace WeChatParking.Core.BLL
{

    /// <summary>
    /// 订单逻辑操作类
    /// </summary>
    public class PrepaidOrder
    {
        /// <summary>
        /// 完成订单支付
        /// </summary>
        /// <param name="order_id">订单Id</param>
        /// <param name="amount">支付金额</param>
        /// <param name="serialNum">支付序列号</param>
        /// <param name="payType">支付类型</param>
        public void HandleOrder(string order_id, decimal amount, string serialNum, WeChatParking.Entity.Enums.PayType payType, bool isTK = false)
        {
            Entity.Order_info order = GetOrder(order_id);
            if (order == null)
            {
                throw new Exception("订单不存在");
            }
            //判断订单是否已经处理过，根据是否已付款来判断
            if (order.pay_status != (short)WeChatParking.Entity.Enums.PayStatus.Payed)
            {
                order.pay_fee = amount;
                order.pay_time = DateTime.Now;
                if (!string.IsNullOrEmpty(serialNum))
                    order.outer_order_id = serialNum;
                order.pay_type = (short)payType;

                if (order.pay_fee < order.real_fee)
                {
                    order.order_status = (short)WeChatParking.Entity.Enums.OrderStatus.Doing;
                    order.pay_status = (short)WeChatParking.Entity.Enums.PayStatus.Partial;
                }
                else
                {
                    order.order_status = (short)WeChatParking.Entity.Enums.OrderStatus.Finish;
                    order.pay_status = (short)WeChatParking.Entity.Enums.PayStatus.Payed;
                }
                //日志
                var log = new Entity.log()
                {
                    business_no = order.order_id,
                    pay_type = order.pay_type,
                    log_date = DateTime.Now,
                    log_type = "订单支付",
                    request = serialNum,
                    message = amount.ToString()
                };
                var carbll = new Core.BLL.CarRecord();
                //修改进场记录
                Entity.CarRecord car = carbll.Get(order.Guid);
                car.Y_fee += amount;
                car.YH_fee += 0.00m;
                car.S_fee += amount;
                //下发缴费记录
                Entity.Api.YPay ypay = new Entity.Api.YPay()
                {
                    DeviceClient_code = car.retain2,
                    EnterpriseID = car.Enterprise_ID,
                    State = 1,
                    Car_plate = car.carBrand,
                    Time = DateTime.Now.ToString("yyyyMMddHHmm"),
                    Fee = Convert.ToInt32(amount * 100),
                    CarUser_type = string.IsNullOrWhiteSpace(order.order_note) ? 1 : 9,//9开闸
                    order_id = order.order_id,
                    Guid = Guid.NewGuid().ToString("N"),
                    create_time = DateTime.Now,
                };
                //如果是现场扫码支付找出所在的客户端
                if (!string.IsNullOrWhiteSpace(order.order_note))
                {
                    ypay.DeviceClient_code = new Core.BLL.Device().GetDeviceClient_code(order.order_note);
                }
                using (var dbContext = Repository.DbContext.Create())
                {
                    dbContext.RunInTransaction(() =>
                    {
                        dbContext.Insert(log);
                        dbContext.Update(order);
                        dbContext.Update(car);
                        dbContext.Insert(ypay);
                    });
                }
                //下发微信通知
                SendNotifyMsg(order);
            }
            else
            {
                if (isTK)
                {
                    order.order_status = 5;
                    order.pay_status = 4;
                    //日志
                    var log = new Entity.log()
                    {
                        business_no = order.order_id,
                        pay_type = order.pay_type,
                        log_date = DateTime.Now,
                        log_type = "订单退款--原始记录：" + order_id,
                        request = serialNum,
                        message = amount.ToString()
                    };
                    using (var dbContext = Repository.DbContext.Create())
                    {
                        dbContext.RunInTransaction(() =>
                        {
                            dbContext.Insert(log);
                            dbContext.Update(order);
                        });
                    }
                }
            }
        }

        /// <summary>
        /// 创建新订单
        /// </summary>
        /// <param name="operateUserId">操作员ID</param>
        /// <param name="carReID">进场记录ID</param>
        /// <param name="total_fee">订单金额</param>
        /// <param name="order_note">订单备注：支付接口接口加密串</param>
        /// <param name="discount_fee">优惠金额</param>
        /// <returns></returns>
        public Entity.Order_info CreateOrder(int operateUserId, int carReID, decimal total_fee, string order_note, decimal discount_fee = 0, bool isUnionPay = false)
        {
            try
            {
                var userbll = new Core.BLL.Wx_user();
                var Openuser = userbll.GetWxUserById(operateUserId);
                if (Openuser == null) return null;
                var carbll = new Core.BLL.CarRecord();
                var carRe = carbll.Get(carReID);
                if (carRe == null) return null;
                var enbll = new Core.BLL.Enterprise();
                var CCen = enbll.Get(String.Format(" Enterprise_Name='{0}'", carRe.Enterprise_Name), "").FirstOrDefault();
                if (CCen == null) return null;
                Entity.Order_info order = new Entity.Order_info()
                {
                    order_id = this.GenOrderId(operateUserId),
                    Wxuser_id = Openuser.id,
                    Wxuser_name = Openuser.nickname,
                    car_no = carRe.carBrand,
                    EnterpriseID = carRe.Enterprise_ID,
                    CCEnterpriseID = CCen.ID,
                    total_fee = total_fee,
                    discount_fee = discount_fee,
                    real_fee = total_fee - discount_fee,
                    pay_fee = 0M,
                    order_status = (short)Entity.Enums.OrderStatus.UnPay,
                    pay_status = (short)Entity.Enums.PayStatus.UnPay,
                    create_time = DateTime.Now,
                    create_user = Openuser.nickname,
                    update_time = DateTime.Now,
                    update_user = Openuser.nickname,
                    version = 0,
                    Guid = carRe.Guid,
                    order_note = order_note,
                    pay_type = (Int16)(isUnionPay ? 5 : 0),
                };
                //如果是现场扫码支付找出所在的客户端
                if (!string.IsNullOrWhiteSpace(order.order_note))
                {
                    //判断二维码的支付的api是否有效
                    string DeviceClient_code = new Core.BLL.Device().GetDeviceClient_code(order.order_note);
                    if (string.IsNullOrWhiteSpace(DeviceClient_code))
                    {
                        throw new Exception("二维码已失效");
                    }
                }
                using (var dbContext = Repository.DbContext.Create())
                {
                    dbContext.Insert(order, null);
                }
                return order;
            }
            catch (Exception ex)
            {

                LogHelper.Error(ex, "创建订单");

                return null;
            }
        }
        /// <summary>
        /// 生成新订单Id。 
        /// </summary>
        /// <returns></returns>
        private string GenOrderId(int userId)
        {
            var now = DateTime.Now;
            var tick = Util.Comm.GetTimeStamp(now).ToString();
            var ran = new Random().Next(99);
            var ids = "000" + userId.ToString();
            //update NickWang 在新订单号中家入后缀（停车场代码）
            //return now.ToString("MMDD")
            //    + tick.Substring(tick.Length - 6)
            //    + ran.ToString().PadLeft(2, '0')
            //    + ids.Substring(ids.Length - 4)
            //    +"ParkingCode";
            return now.ToString("MMdd")
                + tick.Substring(tick.Length - 6)
                + ran.ToString().PadLeft(2, '0')
                + ids.Substring(ids.Length - 4);
            //return DateTime.Now.ToString("yyMMddHHmmssfff") + (userId % 100000).ToString().PadLeft(5, '0');
            /*
            string flagStr = "9";   //订单
            string newId = flagStr + DateTime.Today.ToString("yyMMdd");
            DateTime now = DateTime.Now;

            string maxOrderId =this.orderDal.GetMaxOrderId();
            if (string.IsNullOrEmpty(maxOrderId) || !maxOrderId.StartsWith(newId) || maxOrderId.Length < 5)
            {
                newId += "00001";
            }
            else
            {
                string seqNum = maxOrderId.Substring(maxOrderId.Length - 5);
                newId += (Int32.Parse(seqNum) + 1).ToString().PadLeft(5, '0');
            }

            return newId;
            */
        }

        public Entity.Order_info GetOrder(string orderid)
        {
            if (string.IsNullOrWhiteSpace(orderid))
                return null;
            using (var dbContext = Repository.DbContext.Create())
            {
                return dbContext.Get<Entity.Order_info>(orderid, null);
            }
        }

        public bool Update(Entity.Order_info order)
        {
            using (var dbContext = Repository.DbContext.Create())
            {
                return dbContext.Update(order);
            }
        }
        /// <summary>
        /// 发送微信通知：出场缴费成功
        /// </summary>
        /// <param name="order"></param>
        private void SendNotifyMsg(Entity.Order_info order)
        {
            try
            {
                using (var dbContext = Repository.DbContext.Create())
                {

                    var userInfo = dbContext.Get<Entity.Wx_user>(order.Wxuser_id, null);
                    if (userInfo != null)
                    {
                        var ent = dbContext.Get<Entity.Enterprise>(order.CCEnterpriseID, null);
                        var msg = new Entity.DBGen.WXNotifyMsg()
                        {
                            MsgType = "WxCarPayOut",
                            Wx_userID = userInfo.id,
                            OpenId = userInfo.openid,
                            SendState = (byte)MsgSendState.Waiting,
                            LeaveTry = 0x01,
                            Content = Util.Conv.ToJson(new
                            {
                                first = "缴费成功，请在15分钟内驶离停车场",
                                keyword1 = order.car_no,
                                keyword2 = ent.Enterprise_Name,
                                keyword3 = order.pay_fee,
                                keyword4 = order.discount_fee,
                                keyword5 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                remark = "祝您出行顺利，一路平安！"
                            }),
                            CreateTime = DateTime.Now,
                            CreateUser = "SERVER",
                        };
                        dbContext.Insert(msg);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "微信推送消息写入");
            }
        }
    }
}
